package com.kkwrite.regimen.provider.service.message;

import com.kkwrite.regimen.common.entity.dto.ShopMessageOutDTO;
import com.kkwrite.regimen.provider.domain.RegShopMessageDO;
import com.kkwrite.regimen.provider.exception.ServiceException;
import com.kkwrite.regimen.provider.repository.RegShopMessageRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Ron on 2018/8/26 12:36.
 *
 * @author Ron
 */
@Service("shopMessageService")
public class ShopMessageServiceImpl implements ShopMessageService {

    @Resource(name = "regShopMessageRepository")
    private RegShopMessageRepository messageRepository;

    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = true)
    public ShopMessageOutDTO queryPageable(Integer shopId, Integer page, Integer pageSize) {
        RegShopMessageDO example = new RegShopMessageDO();
        example.setShopId(shopId);
        Page<RegShopMessageDO> pageContent = messageRepository.findAll(Example.of(example),
                PageRequest.of(page, pageSize, new Sort(Sort.Direction.DESC, "gmtCreate")));
        if (!pageContent.hasContent()) {
            throw new ServiceException("该店铺无消息记录");
        }
        int totalPages = pageContent.getTotalPages();
        long totalElements = pageContent.getTotalElements();
        ShopMessageOutDTO outDTO = new ShopMessageOutDTO();
        outDTO.setTotalPages(totalPages);
        outDTO.setTotalElements(totalElements);
        List<ShopMessageOutDTO.OutData> outList = outDTO.getElementList();
        pageContent.getContent().parallelStream().forEach((messageDO) -> {
            ShopMessageOutDTO.OutData out = outDTO.getOutData();
            BeanUtils.copyProperties(messageDO, out);
            out.setCreateTime(messageDO.getGmtCreate().toLocalDateTime());
            outList.add(out);
        });
        return outDTO;
    }

}
